package com.sghd.candy.module.fight.manager;

import com.sghd.common.ramcache.anno.Inject;
import com.sghd.common.ramcache.service.EntityCacheService;
import com.sghd.common.socket.handler.filter.firewall.IpFilter;
import com.sghd.pojo.candy.fight.enums.BattleResult;
import com.sghd.pojo.candy.fight.enums.RoomStatus;
import com.sghd.pojo.fight.game.RoomType;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;

/**
 * @author Allen
 * @date 2018/12/03
 */
@Component
public class FightManager implements IpFilter{
    @Inject
    private EntityCacheService<Long, FightInfo> fightInfoCache;
    @Inject
    private EntityCacheService<Integer, ServerConfig> fightServerCache;


    public FightInfo load(long playerId) {
        return fightInfoCache.loadOrCreate(playerId, builder -> FightInfo.valueOf(playerId));
    }

    public ServerConfig load(int serverId) {
        return fightServerCache.load(serverId);
    }

    public ServerConfig getAvailableServer() {
        Set serverSet = fightServerCache.getFinder().find(fightServer -> {
                    if (fightServer.getRoomStatus() == RoomStatus.OPEN) {
                        if (fightServer.getOnLineCount() >= fightServer.getMaxLimit()) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return true;
                    }
                }
        );

        Iterator<ServerConfig> iterator = serverSet.iterator();

        while (iterator.hasNext()) {
            return iterator.next();
        }

        return null;
    }

    public void connect(FightInfo fightInfo, RoomType roomType, int serverId) {
        fightInfo.connect(serverId, roomType);
    }

    public void disConnect(FightInfo fightInfo) {
        fightInfo.disConnect();
    }

    public void pvpSettlement(FightInfo fightInfo, BattleResult battleResult) {
        fightInfo.pvpSettlement(battleResult);
    }

    public void pveSettlement(FightInfo fightInfo, int addGrade) {
        fightInfo.pveSettlement(addGrade);
    }

    @Override
    public boolean match(String ip) {
        Set servers = fightServerCache.getFinder().find(
                fightServer -> !fightServer.getServerIp().equals(ip));
        return !servers.isEmpty();
    }
}
